package com.atguigu.medical.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.medical.realtime.app.BaseApp;
import com.atguigu.medical.realtime.bean.TradeDoctorConsultationPayBean;
import com.atguigu.medical.realtime.common.Constant;
import com.atguigu.medical.realtime.function.AsyncDimFunction;
import com.atguigu.medical.realtime.util.DateUtil;
import com.atguigu.medical.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2023/4/28 14:47
 */
public class DwsTradeDoctorConsultationPayWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeDoctorConsultationPayWindow().init(
            40011,
            2,
            "DwsTradeDoctorConsultationPayWindow",
            Constant.TOPIC_DWD_TRADE_CONSULTATION_FEE_PAY_SUCCESS
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 把数据封装为 pojo 类型
        SingleOutputStreamOperator<TradeDoctorConsultationPayBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<TradeDoctorConsultationPayBean> beanStreamWithoutDims = windowAndAgg(beanStream);
        // 3. 补充维度
          SingleOutputStreamOperator<TradeDoctorConsultationPayBean> resultStream = joinDims(beanStreamWithoutDims);
        // 4. 写出到 clickhouse 中
          writeToClickHouse(resultStream);
    }
    
    private SingleOutputStreamOperator<TradeDoctorConsultationPayBean> joinDims(
        SingleOutputStreamOperator<TradeDoctorConsultationPayBean> stream) {
        SingleOutputStreamOperator<TradeDoctorConsultationPayBean> doctorStream = AsyncDataStream.unorderedWait(
            stream,
            new AsyncDimFunction<TradeDoctorConsultationPayBean>() {
                @Override
                public String getTable() {
                    return "dim_doctor";
                }
                
                @Override
                public String getId(TradeDoctorConsultationPayBean bean) {
                    return bean.getDoctorId();
                }
                
                @Override
                public void addDim(TradeDoctorConsultationPayBean bean, JSONObject dim) {
                    bean.setDoctorName(dim.getString("NAME"));
                    bean.setHospitalId(dim.getString("HOSPITAL_ID"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
        return AsyncDataStream.unorderedWait(
            doctorStream,
            new AsyncDimFunction<TradeDoctorConsultationPayBean>() {
                @Override
                public String getTable() {
                    return "dim_hospital";
                }
                
                @Override
                public String getId(TradeDoctorConsultationPayBean bean) {
                    return bean.getHospitalId();
                }
                
                @Override
                public void addDim(TradeDoctorConsultationPayBean bean, JSONObject dim) {
                    bean.setHospitalName(dim.getString("NAME"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
    }
    
    
    private void writeToClickHouse(SingleOutputStreamOperator<TradeDoctorConsultationPayBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_doctor_consultation_pay_window", TradeDoctorConsultationPayBean.class));
    }
    
    private SingleOutputStreamOperator<TradeDoctorConsultationPayBean> windowAndAgg(
        SingleOutputStreamOperator<TradeDoctorConsultationPayBean> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeDoctorConsultationPayBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(TradeDoctorConsultationPayBean::getDoctorId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeDoctorConsultationPayBean>() {
                    @Override
                    public TradeDoctorConsultationPayBean reduce(TradeDoctorConsultationPayBean value1,
                                                                 TradeDoctorConsultationPayBean value2) throws Exception {
                        value1.setConsultationPayCt(value1.getConsultationPayCt() + value2.getConsultationPayCt());
                        value1.setConsultationPayAmount(value1.getConsultationPayAmount().add(value2.getConsultationPayAmount()));
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeDoctorConsultationPayBean, TradeDoctorConsultationPayBean, String, TimeWindow>() {
                    @Override
                    public void process(String doctorId,
                                        Context ctx,
                                        Iterable<TradeDoctorConsultationPayBean> elements,
                                        Collector<TradeDoctorConsultationPayBean> out) throws Exception {
                        TradeDoctorConsultationPayBean bean = elements.iterator().next();
                        
                        bean.setStt(DateUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(DateUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<TradeDoctorConsultationPayBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(new MapFunction<String, TradeDoctorConsultationPayBean>() {
                @Override
                public TradeDoctorConsultationPayBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    
                    return TradeDoctorConsultationPayBean.builder()
                        .doctorId(obj.getString("doctor_id"))
                        .consultationPayCt(1L)
                        .consultationPayAmount(obj.getBigDecimal("payment_amount"))
                        .ts(obj.getLong("ts"))
                        .build();
                }
            });
    }
}
